const { queryPhone } = require('../../util/phone');
const dyPuptr = require("./dyPuptr")
const dyApi = require("./dyApi");
const webSockt = require('./webSockt')
const smsApi = require("./smsApi")
const serApi = require("./serApi")
const cache = require('../../util/cache')
const sleep = require("../../util/sleep");

async function init() {
    await dyPuptr.puptrInit();
}

async function getUsers(urlParam, header, num, taskId, orderId, code, apiKey) {
    console.log("getUsers: num = " + num + ", taskId = " + taskId + ", orderId = " + orderId + ", code = " + code + ", apiKey = " + apiKey);

    let result = await getIPsetProxy(orderId, code, apiKey);
    if (result.code != 0) {
        return result;
    }

    result = await dyApi.feedFirstList(urlParam, header);
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }

    let userInfo = { code: 0, data: { taskId: taskId, rows: [] }, msg: '' };
    let arr = result.data;
    for (let itm of arr) {
        let len = 0, cnt = 0;

        do {
            result = await dyApi.commentList(urlParam, header, itm, cnt);
            if (result.code != 0) {
                console.log(result.msg);
                return result;
            } else {
                userInfo.data.rows = userInfo.data.rows.concat(result.data);
                len = result.data.length;
                if (len < 20) {
                    break;
                } else {
                    cnt += 20;
                }
            }
            await sleep(1000);
        } while (len == 20 && (userInfo.data.rows.length < num));

        if (userInfo.data.rows.length >= num) {
            break;
        }
    }

    return userInfo;
}

async function getVideoInfo(url) {
    console.log("getVideoInfo: url = " + url);
    let videoInfo = cache.get(url);
    if (videoInfo == null) {
        let result = await dyPuptr.getVideoInfo(url);
        if (result.code == 0) {
            videoInfo = result.data;
            cache.set(url, videoInfo);
        }
    }

    return videoInfo;
}

async function followUser(url, urlParam, header, orderId, code, apiKey) {
    console.log("followUser: url = " + url + ", orderId = " + orderId + ", code = " + code + ", apiKey = " + apiKey);
    let videoInfo = cache.get(url);
    if (videoInfo == null) {
        videoInfo = await getVideoInfo(url);
    }

    let result = await getIPsetProxy(orderId, code, apiKey);
    if (result.code != 0) {
        return result;
    }

    result = await dyApi.getUserInfoByUserId(urlParam, header, videoInfo.uid);
    let secUserId = result.sec_uid;
    await sleep(1000);
    return dyApi.followUser(urlParam, header, 1, videoInfo.uid, secUserId);
}

async function diggVideo(url, urlParam, header, orderId, code, apiKey) {
    console.log("diggVideo: url = " + url + ", orderId = " + orderId + ", code = " + code + ", apiKey = " + apiKey);
    let videoInfo = cache.get(url);
    if (videoInfo == null) {
        videoInfo = await getVideoInfo(url);
    }

    let result = await getIPsetProxy(orderId, code, apiKey);
    if (result.code != 0) {
        return result;
    }

    return await dyApi.diggVideo(urlParam, header, videoInfo.statistics.aweme_id, 1);
}

async function commentVideo(url, urlParam, header, comment, orderId, code, apiKey) {
    console.log("commentVideo: url = " + url + ", comment = " + comment + ", orderId = " + orderId + ", code = " + code + ", apiKey = " + apiKey);
    let videoInfo = cache.get(url);
    if (videoInfo == null) {
        videoInfo = await getVideoInfo(url);
    }

    let result = await getIPsetProxy(orderId, code, apiKey);
    if (result.code != 0) {
        return result;
    }

    return await dyApi.commentVideo(urlParam, header, videoInfo.statistics.aweme_id, comment);
}

async function message(phone, password, device, pList) {
    let phoneInfo = await queryPhone(phone);
    console.log("message: phone = " + phone + ', phoneInfo = ' + JSON.stringify(phoneInfo) + ", password = " + password + ", device = " + device + ", pList = " + JSON.stringify(pList));
    let result = await webSockt.message(phone, password, device, phoneInfo, pList);
    // if (result.code != 0) {
    //     await webSockt.exit();
    // };
    return result;
}

async function login(phone, password, device) {
    let phoneInfo = await queryPhone(phone);
    console.log("login: phone = " + phone + ', phoneInfo = ' + JSON.stringify(phoneInfo) + ", password = " + password + ", device = " + device);
    let result = await webSockt.login(phone, password, device, phoneInfo);
    // if (result.code != 0) {
    //     await webSockt.exit();
    // };
    return result;
}

async function register(num) {
    console.log("register: num = " + num);
    for (let index = 0; index < num; index++) {
        console.log('register: ' + (index + 1) + ' / ' + num);
        let result = await registerOne();
        if (result.code != 0) {
            await webSockt.exit();
        }
    }
}

async function registerOne() {
    let result = await webSockt.waitLite();
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }

    result = await smsApi.login();
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }
    let token = result.token;

    // result = await smsApi.cancelAllRecv(token);
    // if (result.code != 0) {
    //     console.log(result.msg);
    //     return result;
    // }

    result = await smsApi.getPhone(token);
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }
    let phone = result.phone;
    let phoneInfo = await queryPhone(phone);
    console.log('phone = ' + phone + ', phoneInfo = ' + JSON.stringify(phoneInfo));
    result = await webSockt.sendCode(phone, phoneInfo, null);
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }

    let yzm = "";
    for (let i = 0; i < 8; i++) {
        await sleep(10 * 1000);
        result = await smsApi.getMessage(token, phone);
        if (result.code == 0) {
            yzm = result.sms.getMidText("验证码", "，");
            break;
        } else {
            console.log(result.msg);
        }
    }
    if (yzm == "") {
        result = { code: 1, data: '', msg: '验证码获取失败' };
        console.log(result.msg);
        return result;
    }

    let password = "aa123123";
    result = await webSockt.smsReg(yzm, password);
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }

    result = await smsApi.getPhone(token, phone);
    if (result.code != 0) {
        console.log(result.msg);
        return result;
    }
    phone = result.phone;

    yzm = "";
    for (let i = 0; i < 8; i++) {
        await sleep(10 * 1000);
        result = await smsApi.getMessage(token, phone);
        if (result.code == 0) {
            yzm = result.sms.getMidText("验证码", "，");
            break;
        } else {
            console.log(result.msg);
        }
    }
    if (yzm == "") {
        result = { code: 1, data: '', msg: '验证码获取失败' };
        console.log(result.msg);
        return result;
    }

    result = await webSockt.smsUpdatePassword(yzm);
    if (result.code != 0) {
        console.log(result.msg);
    }

    await serApi.registerLoginRes(true, phone, password, result.data.urlParam, result.data.header);
    await smsApi.addBlacklist(token, phone);
    return result;
}
/**
 * 
 * @param {*} orderId 代理订单号
 * @param {*} code 地区编码
 * @param {*} apiKey 代理Api Key
 */
async function getIPsetProxy(orderId, code, apiKey) {
    let result;
    let key = orderId + ',' + code;
    console.log('proxy: param key = ' + key);

    let ip = cache.get(key);
    if (ip != null) {
        console.log('proxy: cache ip = ' + ip);
        result = await dyApi.getdpsvalidtime(orderId, ip, apiKey);
        if (result.code == 0) {
            let time = result.data[ip];
            console.log('proxy: valid time = ' + time);
            if (time < 60) {
                ip = null;
                cache.del(key)
            } else {
                dyApi.setProxy(ip);
                console.log('proxy: result ip = ' + ip);
            }
        } else {
            ip = null;
            cache.del(key)
        }
    }

    if (ip == null) {
        console.log('proxy: get new ip');
        result = await dyApi.getdps(orderId, code, apiKey);
        if (result.code == 0) {
            ip = result.data.proxy_list[0];
            cache.set(key, ip);
            dyApi.setProxy(ip);
            console.log('proxy: result ip = ' + ip);
        }
    }

    return result;
}

module.exports = {
    init,
    getUsers,
    getVideoInfo,
    followUser,
    diggVideo,
    commentVideo,
    message,
    login,
    register,
}